<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>整合式贪吃蛇游戏</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <style>
        /* 网页样式 */
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            background: #2c3e50;
            margin: 0;
            font-family: Arial, sans-serif;
        }

        #gameContainer {
            margin-top: 20px;
        }

        #gameCanvas {
            border: 3px solid #34495e;
            border-radius: 5px;
            box-shadow: 0 0 20px rgba(0,0,0,0.3);
        }

        #scoreBoard {
            color: #ecf0f1;
            font-size: 24px;
            margin: 10px 0;
        }

        .controls {
            color: #bdc3c7;
            margin-top: 15px;
        }
    </style>
</head>
<body>
    <div id="scoreBoard">得分: 0</div>
    <div id="gameContainer">
        <canvas id="gameCanvas" width="400" height="400"></canvas>
    </div>
    <div class="controls">使用方向键控制移动</div>

    <script>
        // 游戏初始化
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const GRID_SIZE = 20;
        const GRID_COUNT = canvas.width / GRID_SIZE;

        let snake = [
            { x: 10, y: 10 },
            { x: 9, y: 10 },
            { x: 8, y: 10 }
        ];
        let food = generateFood();
        let direction = 'right';
        let score = 0;
        let gameLoopId;

        // 食物生成（避免与蛇身重叠）
        function generateFood() {
            while(true) {
                const newFood = {
                    x: Math.floor(Math.random() * GRID_COUNT),
                    y: Math.floor(Math.random() * GRID_COUNT)
                };
                if (!snake.some(segment => segment.x === newFood.x && segment.y === newFood.y)) {
                    return newFood;
                }
            }
        }

        // 游戏绘制
        function draw() {
            // 清空画布
            ctx.fillStyle = '#34495e';
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            // 绘制蛇身
            snake.forEach((segment, index) => {
                ctx.fillStyle = index === 0 ? '#2ecc71' : '#27ae60';
                ctx.fillRect(
                    segment.x * GRID_SIZE,
                    segment.y * GRID_SIZE,
                    GRID_SIZE - 1,
                    GRID_SIZE - 1
                );
            });

            // 绘制食物
            ctx.fillStyle = '#e74c3c';
            ctx.fillRect(
                food.x * GRID_SIZE,
                food.y * GRID_SIZE,
                GRID_SIZE - 1,
                GRID_SIZE - 1
            );
        }

        // 游戏逻辑更新
        function update() {
            const head = { ...snake[0] };

            // 方向控制
            switch(direction) {
                case 'up': head.y--; break;
                case 'down': head.y++; break;
                case 'left': head.x--; break;
                case 'right': head.x++; break;
            }

            // 碰撞检测
            if (head.x < 0 || head.x >= GRID_COUNT || 
                head.y < 0 || head.y >= GRID_COUNT ||
                snake.some(segment => segment.x === head.x && segment.y === head.y)) {
                alert(`游戏结束！得分: ${score}`);
                resetGame();
                return;
            }

            snake.unshift(head);

            // 吃食物逻辑
            if (head.x === food.x && head.y === food.y) {
                score += 10;
                document.getElementById('scoreBoard').textContent = `得分: ${score}`;
                food = generateFood();
            } else {
                snake.pop();
            }
        }

        // 游戏控制
        function startGame() {
            if (!gameLoopId) {
                gameLoopId = setInterval(() => {
                    update();
                    draw();
                }, 150);
            }
        }

        function resetGame() {
            clearInterval(gameLoopId);
            gameLoopId = null;
            snake = [
                { x: 10, y: 10 },
                { x: 9, y: 10 },
                { x: 8, y: 10 }
            ];
            direction = 'right';
            score = 0;
            document.getElementById('scoreBoard').textContent = '得分: 0';
            startGame();
        }

        // 事件监听
        document.addEventListener('keydown', (event) => {
            const oldDirection = direction;
            switch(event.key) {
                case 'ArrowUp':
                    if (direction !== 'down') direction = 'up';
                    break;
                case 'ArrowDown':
                    if (direction !== 'up') direction = 'down';
                    break;
                case 'ArrowLeft':
                    if (direction !== 'right') direction = 'left';
                    break;
                case 'ArrowRight':
                    if (direction !== 'left') direction = 'right';
                    break;
            }
            if (oldDirection !== direction) startGame();
        });

        // 初始绘制
        draw();
    </script>
</body>
</html>